package com.campus.client.view;

import com.campus.client.controller.LibraryController;
import com.campus.client.net.ClientConnector;
import com.campus.common.vo.Book;
import com.campus.common.vo.BorrowRecord;
import com.campus.common.vo.User;
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.*;
import javafx.stage.Stage;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

public class LibraryAdminFrame {
    private LibraryController libraryController;
    private GridPane bookGrid;
    private ScrollPane scrollPane;
    private MenuBar menuBar;
    private Button backBtn;
    private final int COLS = 2; // 每行2个书籍
    private List<Book> currentBooks;
    private ComboBox<String> categoryComboBox;
    private User user=new User();
    public User getUser() {return user;}
    public void setUser(String Id,String password,String role) {
        this.user.setId(Id);
        this.user.setPassword(password);
        this.user.setRole(role);
        //System.out.print("用户名"+this.user.getId());
    }


    public void start(Stage primaryStage) throws Exception {
        // 初始化 LibraryController
        libraryController = new LibraryController(new ClientConnector("172.20.10.2", 8888));

        BorderPane root = new BorderPane();
        root.setPadding(new Insets(10));
        root.getStyleClass().add("main-container");

        // 顶部标题栏
        HBox headerBox = new HBox();
        headerBox.getStyleClass().add("header-box");
        headerBox.setAlignment(Pos.CENTER_LEFT);
        headerBox.setPadding(new Insets(10, 15, 10, 15));

        Label titleLabel = new Label("校园图书馆 - 管理员版");
        titleLabel.getStyleClass().add("header-title");

        Region spacer = new Region();
        HBox.setHgrow(spacer, Priority.ALWAYS);

        // 创建菜单栏
        menuBar = createMenuBar();

        Region buttonSpacer = new Region();
        buttonSpacer.setPrefWidth(10);

        backBtn = createStyledButton("返回");
        backBtn.getStyleClass().add("secondary-button");
        backBtn.setOnAction(e -> {
            try {
                back();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });

        headerBox.getChildren().addAll(titleLabel, spacer, menuBar, buttonSpacer, backBtn);
        root.setTop(headerBox);

        // 内容区域
        VBox contentBox = new VBox();
        contentBox.getStyleClass().add("content-box");
        contentBox.setPadding(new Insets(15));

        // 添加搜索面板
        HBox searchPanel = createSearchPanel();
        contentBox.getChildren().add(searchPanel);

        // 书籍网格显示区域
        bookGrid = new GridPane();
        bookGrid.setHgap(20);
        bookGrid.setVgap(20);
        bookGrid.setPadding(new Insets(10));
        bookGrid.setAlignment(Pos.TOP_CENTER);

        // 设置列约束，使两列等宽
        ColumnConstraints col1 = new ColumnConstraints();
        col1.setPercentWidth(50);
        ColumnConstraints col2 = new ColumnConstraints();
        col2.setPercentWidth(50);
        bookGrid.getColumnConstraints().addAll(col1, col2);

        scrollPane = new ScrollPane(bookGrid);
        scrollPane.getStyleClass().add("scroll-pane");
        scrollPane.setFitToWidth(true);

        contentBox.getChildren().add(scrollPane);
        root.setCenter(contentBox);

        // 默认加载所有书籍
        loadAllBooks();

        Scene scene = new Scene(root, 1000, 600);
        scene.getStylesheets().add(getClass().getResource("/css/style.css").toExternalForm());
        primaryStage.setTitle("校园图书馆 - 管理员版");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    // 创建菜单栏
    private MenuBar createMenuBar() {
        MenuBar menuBar = new MenuBar();
        menuBar.getStyleClass().add("library-menu-bar");

        Menu allBooksMenu = new Menu("显示操作");

        MenuItem allBooksItem = new MenuItem("显示所有书籍");
        allBooksItem.setOnAction(e -> loadAllBooks());

        // 新增排序和筛选菜单项
        MenuItem sortByTitleItem = new MenuItem("按书名排序");
        sortByTitleItem.setOnAction(e -> sortBooksByTitle());

        MenuItem sortByAuthorItem = new MenuItem("按作者排序");
        sortByAuthorItem.setOnAction(e -> sortBooksByAuthor());

        MenuItem filterAvailableItem = new MenuItem("筛选可借阅");
        filterAvailableItem.setOnAction(e -> filterAvailableBooks());

        allBooksMenu.getItems().addAll(allBooksItem, sortByTitleItem, sortByAuthorItem, filterAvailableItem);

        Menu manageMenu = new Menu("管理");
        MenuItem addBookItem = new MenuItem("新增书籍");
        addBookItem.setOnAction(e -> showAddBookDialog());
        manageMenu.getItems().add(addBookItem);

        menuBar.getMenus().addAll(allBooksMenu, manageMenu);
        return menuBar;
    }
    private void sortBooksByTitle() {
        if (currentBooks == null || currentBooks.isEmpty()) return;

        currentBooks.sort((b1, b2) -> {
            java.text.Collator collator = java.text.Collator.getInstance(java.util.Locale.CHINA);
            return collator.compare(b1.getTitle(), b2.getTitle());
        });

        displayBooks(currentBooks, "按书名排序");
    }

    private void sortBooksByAuthor() {
        if (currentBooks == null || currentBooks.isEmpty()) return;

        currentBooks.sort((b1, b2) -> {
            java.text.Collator collator = java.text.Collator.getInstance(java.util.Locale.CHINA);
            return collator.compare(b1.getAuthor(), b2.getAuthor());
        });

        displayBooks(currentBooks, "按作者排序");
    }

    private void filterAvailableBooks() {
        if (currentBooks == null || currentBooks.isEmpty()) return;

        List<Book> availableBooks = new ArrayList<>();
        for (Book book : currentBooks) {
            if (book.isAvailable() && book.getStock() > 0) {
                availableBooks.add(book);
            }
        }

        displayBooks(availableBooks, "可借阅书籍");
    }

        // 创建搜索面板
        private HBox createSearchPanel() {
            HBox searchPanel = new HBox(10);
            searchPanel.setPadding(new Insets(10));
            searchPanel.setAlignment(Pos.CENTER_LEFT);
            searchPanel.getStyleClass().add("search-panel");
            TextField searchField = new TextField();
            searchField.setPromptText("输入书名或作者");
            searchField.setPrefWidth(200);

            categoryComboBox = new ComboBox<>();
            categoryComboBox.setPromptText("选择书籍类别");
            categoryComboBox.setPrefWidth(150);

            // 从服务器获取类别列表
            try {
                List<String> categories = libraryController.getAllCategories();
                categoryComboBox.getItems().addAll(categories);
            } catch (Exception ex) {
                ex.printStackTrace();
                showAlert("错误", "获取类别列表失败: " + ex.getMessage(), Alert.AlertType.ERROR);
            }

            Button searchButton = createStyledButton("搜索");
            searchButton.setOnAction(e -> {
                String keyword = searchField.getText().trim();
                if (!keyword.isEmpty()) {
                    try {
                        List<Book> booksByTitle = libraryController.searchBooksByTitle(keyword);
                        List<Book> booksByAuthor = libraryController.searchBooksByAuthor(keyword);

                        // 合并结果，去重
                        Set<Book> resultSet = new HashSet<>();
                        resultSet.addAll(booksByTitle);
                        resultSet.addAll(booksByAuthor);

                        displaySearchResults(new ArrayList<>(resultSet), keyword);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        showAlert("错误", "搜索失败: " + ex.getMessage(), Alert.AlertType.ERROR);
                    }
                }
            });

            // 新增筛选按钮
            Button filterButton = createStyledButton("筛选");
            filterButton.setOnAction(e -> {
                String selectedCategory = categoryComboBox.getValue();
                if (selectedCategory != null && !selectedCategory.isEmpty()) {
                    try {
                        List<Book> booksByCategory = libraryController.searchBooksByCategory(selectedCategory);
                        displaySearchResults(booksByCategory, "类别: " + selectedCategory);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        showAlert("错误", "筛选失败: " + ex.getMessage(), Alert.AlertType.ERROR);
                    }
                } else {
                    showAlert("提示", "请选择书籍类别", Alert.AlertType.INFORMATION);
                }
            });

            Button clearButton = createStyledButton("清除搜索");
            clearButton.setOnAction(e -> {
                searchField.clear();
                categoryComboBox.getSelectionModel().clearSelection();
                loadAllBooks();
            });

            searchPanel.getChildren().addAll(
                    new Label("🔍按书名/作者搜索:"), searchField, searchButton,
                    new Label("🔍按类别筛选:"), categoryComboBox, filterButton, clearButton
            );

            return searchPanel;
        }
    private void displayBooks(List<Book> books, String title) {
        bookGrid.getChildren().clear();

        Label titleLabel = new Label(title);
        titleLabel.getStyleClass().add("category-title");
        bookGrid.add(titleLabel, 0, 0, COLS, 1);

        if (books.isEmpty()) {
            Label noResultLabel = new Label("没有找到相关书籍");
            noResultLabel.getStyleClass().add("empty-label");
            bookGrid.add(noResultLabel, 0, 1, COLS, 1);
        } else {
            for (int i = 0; i < books.size(); i++) {
                Book book = books.get(i);
                VBox bookCard = createBookCard(book);
                int col = i % COLS;
                int row = (i / COLS) + 1;
                bookGrid.add(bookCard, col, row);
            }
        }
    }
    private void updateCategoryComboBox() {
        try {
            List<String> categories = libraryController.getAllCategories();
            String currentValue = categoryComboBox.getValue();

            categoryComboBox.getItems().clear();
            categoryComboBox.getItems().addAll(categories);

            // 尝试恢复之前选择的值
            if (currentValue != null && categories.contains(currentValue)) {
                categoryComboBox.setValue(currentValue);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            showAlert("错误", "更新类别列表失败: " + ex.getMessage(), Alert.AlertType.ERROR);
        }
    }
    // 加载所有书籍
    private void loadAllBooks() {
        bookGrid.getChildren().clear();
        try {
            currentBooks = libraryController.getBooks();
            displayBooks(currentBooks, "所有书籍");
        } catch (Exception e) {
            e.printStackTrace();
            showAlert("错误", "加载书籍失败: " + e.getMessage(), Alert.AlertType.ERROR);
        }
    }

    // 创建书籍卡片
    private VBox createBookCard(Book book) {
        VBox card = new VBox(10);
        card.setPadding(new Insets(15));
        card.getStyleClass().add("book-card");
        card.setMaxWidth(350); // 固定卡片宽度
        card.setMinWidth(350);


        // 书籍信息
        Label titleLabel = new Label(book.getTitle().trim()); // 去除首尾空格
        titleLabel.getStyleClass().add("book-title");
        titleLabel.setWrapText(true);

        Label authorLabel = new Label("作者: " + book.getAuthor().trim()); // 去除首尾空格
        authorLabel.getStyleClass().add("book-author");

        Label availableLabel = new Label("可借状态: " + (book.isAvailable() ? "可借" : "不可借"));
        availableLabel.getStyleClass().add(book.isAvailable() ? "book-available" : "book-unavailable");

        Label stockLabel = new Label("库存: " + book.getStock());
        stockLabel.getStyleClass().add("book-stock");

        Label timeLimitLabel = new Label("可借时长: " + book.getTimeLimit() + "天");
        timeLimitLabel.getStyleClass().add("book-stock");


        // 底部按钮区域
        HBox buttonBox = new HBox(10);
        buttonBox.setAlignment(Pos.CENTER_RIGHT);
        buttonBox.getStyleClass().add("book-card-buttons");
        Button viewBorrowersButton = createStyledButton("查看借阅人");
        viewBorrowersButton.getStyleClass().add("info-button");
        viewBorrowersButton.setOnAction(e -> {
            try {
                // 修改为获取借阅记录详情
                List<BorrowRecord> borrowRecords = libraryController.getBookBorrowers(book.getId());
                showBorrowersDialog(book.getTitle(), borrowRecords);
            } catch (Exception ex) {
                ex.printStackTrace();
                showAlert("错误", "获取借阅人信息失败: " + ex.getMessage(), Alert.AlertType.ERROR);
            }
        });
        // 删除按钮
        Button deleteButton = createStyledButton("删除");
        deleteButton.getStyleClass().add("danger-button");
        deleteButton.setOnAction(e -> {
            try {
                String result = libraryController.deleteBook(book.getId());
                if (result.contains("成功")) {
                    showAlert("成功", result, Alert.AlertType.INFORMATION);
                    // 刷新界面
                    loadAllBooks();
                } else {
                    showAlert("失败", result, Alert.AlertType.ERROR);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                showAlert("错误", "删除失败: " + ex.getMessage(), Alert.AlertType.ERROR);
            }
        });

        // 修改按钮
        Button updateButton = createStyledButton("修改");
        updateButton.getStyleClass().add("primary-button");
        updateButton.setOnAction(e -> {
            showUpdateDialog(book);
        });

        // 使用Region将按钮推到右侧
        Region spacer = new Region();
        HBox.setHgrow(spacer, Priority.ALWAYS);
        buttonBox.getChildren().addAll(spacer, viewBorrowersButton, deleteButton, updateButton);

        card.getChildren().addAll(titleLabel, authorLabel, availableLabel, stockLabel, timeLimitLabel, buttonBox);
        return card;
    }
    private void showBorrowersDialog(String bookTitle, List<BorrowRecord> borrowRecords) {
        Dialog<Void> dialog = new Dialog<>();
        dialog.setTitle("借阅人信息");
        dialog.setHeaderText(bookTitle + "的借阅人列表");

        dialog.getDialogPane().getButtonTypes().add(ButtonType.OK);

        // 创建表格
        TableView<BorrowRecord> table = new TableView<>();
        table.getStyleClass().add("borrowers-table");
        // 用户名列
        TableColumn<BorrowRecord, String> userCol = new TableColumn<>("用户名");
        userCol.setCellValueFactory(new PropertyValueFactory<>("username"));

        // 姓名列 - 使用正确的属性名
        TableColumn<BorrowRecord, String> nameCol = new TableColumn<>("姓名");
        nameCol.setCellValueFactory(new PropertyValueFactory<>("realname")); // 改为realname

        // 借书日期列
        TableColumn<BorrowRecord, Date> borrowDateCol = new TableColumn<>("借书日期");
        borrowDateCol.setCellValueFactory(new PropertyValueFactory<>("borrowDate"));
        borrowDateCol.setCellFactory(column -> new TableCell<BorrowRecord, Date>() {
            @Override
            protected void updateItem(Date item, boolean empty) {
                super.updateItem(item, empty);
                if (empty || item == null) {
                    setText(null);
                } else {
                    setText(new SimpleDateFormat("yyyy-MM-dd").format(item));
                }
            }
        });

        // 归还期限列
        TableColumn<BorrowRecord, Date> dueDateCol = new TableColumn<>("归还期限");
        dueDateCol.setCellValueFactory(new PropertyValueFactory<>("dueDate"));
        dueDateCol.setCellFactory(column -> new TableCell<BorrowRecord, Date>() {
            @Override
            protected void updateItem(Date item, boolean empty) {
                super.updateItem(item, empty);
                if (empty || item == null) {
                    setText(null);
                } else {
                    setText(new SimpleDateFormat("yyyy-MM-dd").format(item));
                }
            }
        });
        TableColumn<BorrowRecord, String> statusCol = new TableColumn<>("状态");
        statusCol.setCellValueFactory(cellData -> {
            BorrowRecord record = cellData.getValue();
            boolean isOverdue = new Date().after(record.getDueDate());
            return new SimpleStringProperty(isOverdue ? "超时" : "未超时");
        });
        table.getColumns().addAll(userCol, nameCol, borrowDateCol, dueDateCol, statusCol);
        table.getItems().addAll(borrowRecords);

        VBox content = new VBox();
        content.getChildren().add(table);
        content.setPadding(new Insets(10));

        dialog.getDialogPane().setContent(content);
        dialog.getDialogPane().setPrefSize(400, 400);
        dialog.showAndWait();
    }
    // 显示搜索结果
    private void displaySearchResults(List<Book> books, String keyword) {
        currentBooks = books;
        displayBooks(books, "搜索包含 '" + keyword + "' 的结果 (" + books.size() + " 本)");
    }

    // 显示新增书籍对话框
    private void showAddBookDialog() {
        Dialog<Book> dialog = new Dialog<>();
        dialog.setTitle("新增书籍");
        dialog.setHeaderText("请输入书籍信息");

        ButtonType addButtonType = new ButtonType("添加", ButtonBar.ButtonData.OK_DONE);
        dialog.getDialogPane().getButtonTypes().addAll(addButtonType, ButtonType.CANCEL);

        GridPane grid = new GridPane();
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(20, 150, 10, 10));
        grid.getStyleClass().add("dialog-form");

        TextField titleField = new TextField();
        titleField.setPromptText("书名");
        TextField authorField = new TextField();
        authorField.setPromptText("作者");
        titleField.getStyleClass().add("form-field");
        authorField.getStyleClass().add("form-field");
        categoryComboBox.getStyleClass().add("category-comboBox");
        Spinner<Integer> stockSpinner = new Spinner<>(0, 1000, 1);
        Spinner<Integer> timeLimitSpinner = new Spinner<>(1, 365, 30);

        // 新增类别下拉框
        ComboBox<String> categoryComboBox = new ComboBox<>();
        categoryComboBox.setEditable(true); // 允许输入新类别
        categoryComboBox.setPromptText("选择或输入类别");

        // 从服务器获取已有类别
        try {
            List<String> categories = libraryController.getAllCategories();
            categoryComboBox.getItems().addAll(categories);
        } catch (Exception ex) {
            ex.printStackTrace();
            showAlert("错误", "获取类别列表失败: " + ex.getMessage(), Alert.AlertType.ERROR);
        }

        grid.add(new Label("书名:"), 0, 0);
        grid.add(titleField, 1, 0);
        grid.add(new Label("作者:"), 0, 1);
        grid.add(authorField, 1, 1);
        grid.add(new Label("库存:"), 0, 2);
        grid.add(stockSpinner, 1, 2);
        grid.add(new Label("可借天数:"), 0, 3);
        grid.add(timeLimitSpinner, 1, 3);
        grid.add(new Label("类别:"), 0, 4);  // 新增
        grid.add(categoryComboBox, 1, 4);   // 新增

        dialog.getDialogPane().setContent(grid);

        dialog.setResultConverter(dialogButton -> {
            if (dialogButton == addButtonType) {
                Book newBook = new Book();
                newBook.setTitle(titleField.getText().trim());
                newBook.setAuthor(authorField.getText().trim());
                newBook.setStock(stockSpinner.getValue());
                newBook.setTimeLimit(timeLimitSpinner.getValue());
                newBook.setAvailable(stockSpinner.getValue() > 0);
                newBook.setCategory(categoryComboBox.getValue());  // 设置类别
                return newBook;
            }
            return null;
        });

        Optional<Book> result = dialog.showAndWait();
        result.ifPresent(book -> {
            try {
                String message = libraryController.addBook(book);
                showAlert("添加结果", message, Alert.AlertType.INFORMATION);
                updateCategoryComboBox();
                loadAllBooks();
            } catch (Exception ex) {
                ex.printStackTrace();
                showAlert("错误", "添加失败: " + ex.getMessage(), Alert.AlertType.ERROR);
            }
        });
    }

    // 显示更新书籍对话框
    private void showUpdateDialog(Book book) {
        Dialog<Book> dialog = new Dialog<>();
        dialog.setTitle("更新书籍信息");
        dialog.setHeaderText("更新书籍信息");

        ButtonType updateButtonType = new ButtonType("更新", ButtonBar.ButtonData.OK_DONE);
        dialog.getDialogPane().getButtonTypes().addAll(updateButtonType, ButtonType.CANCEL);

        GridPane grid = new GridPane();
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(20, 150, 10, 10));

        TextField titleField = new TextField(book.getTitle());
        TextField authorField = new TextField(book.getAuthor());
        Spinner<Integer> stockSpinner = new Spinner<>(0, 1000, book.getStock());
        Spinner<Integer> timeLimitSpinner = new Spinner<>(1, 365, book.getTimeLimit());

        // 新增类别下拉框
        ComboBox<String> categoryComboBox = new ComboBox<>();
        categoryComboBox.setEditable(true); // 允许输入新类别
        categoryComboBox.setValue(book.getCategory()); // 设置当前书籍的类别

        // 从服务器获取已有类别
        try {
            List<String> categories = libraryController.getAllCategories();
            categoryComboBox.getItems().addAll(categories);
        } catch (Exception ex) {
            ex.printStackTrace();
            showAlert("错误", "获取类别列表失败: " + ex.getMessage(), Alert.AlertType.ERROR);
        }

        grid.add(new Label("书名:"), 0, 0);
        grid.add(titleField, 1, 0);
        grid.add(new Label("作者:"), 0, 1);
        grid.add(authorField, 1, 1);
        grid.add(new Label("库存:"), 0, 2);
        grid.add(stockSpinner, 1, 2);
        grid.add(new Label("可借天数:"), 0, 3);
        grid.add(timeLimitSpinner, 1, 3);
        grid.add(new Label("类别:"), 0, 4);  // 新增
        grid.add(categoryComboBox, 1, 4);   // 新增

        dialog.getDialogPane().setContent(grid);

        dialog.setResultConverter(dialogButton -> {
            if (dialogButton == updateButtonType) {
                book.setTitle(titleField.getText().trim());
                book.setAuthor(authorField.getText().trim());
                book.setStock(stockSpinner.getValue());
                book.setTimeLimit(timeLimitSpinner.getValue());
                book.setAvailable(stockSpinner.getValue() > 0);
                book.setCategory(categoryComboBox.getValue());  // 设置类别
                return book;
            }
            return null;
        });

        Optional<Book> result = dialog.showAndWait();
        result.ifPresent(updatedBook -> {
            try {
                String message = libraryController.updateBook(updatedBook);
                showAlert("更新结果", message, Alert.AlertType.INFORMATION);
                updateCategoryComboBox();
                loadAllBooks();
            } catch (Exception ex) {
                ex.printStackTrace();
                showAlert("错误", "更新失败: " + ex.getMessage(), Alert.AlertType.ERROR);
            }
        });
    }


    // 统一按钮创建方法
    private Button createStyledButton(String text) {
        Button button = new Button(text);
        button.getStyleClass().add("styled-button");
        return button;
    }

    // 统一提示对话框
    private void showAlert(String title, String message, Alert.AlertType type) {
        Alert alert = new Alert(type, message, ButtonType.OK);
        alert.setHeaderText(title);
        alert.showAndWait();
    }

    public void back() throws IOException {
        // 获取当前登录窗口的Stage
        Stage libraryAdminStage = (Stage) backBtn.getScene().getWindow();

        AdminMainFrame adminMainFrame = new AdminMainFrame();
        adminMainFrame.setUser(user.getId(),user.getPassword(),user.getRole());

        Stage stage = new Stage();
        adminMainFrame.show(stage);

        libraryAdminStage.close();
    }

}